package com.xgq.drink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xgq.drink.entity.Brand;
import com.xgq.drink.entity.Product;
import com.xgq.drink.entity.R;
import com.xgq.drink.entity.Role;
import com.xgq.drink.entity.UserRole;
import com.xgq.drink.mapper.BrandMapper;
import com.xgq.drink.mapper.ProductMapper;
import com.xgq.drink.mapper.RoleMapper;
import com.xgq.drink.mapper.UserRoleMapper;
import com.xgq.drink.service.IBrandService;
import com.xgq.drink.utils.RUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 品牌表 服务实现类
 * </p>
 *
 * @author xgq
 * @since 2025-03-11
 */
@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements IBrandService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R createBrand(Brand brand) {
        if (brand == null || brand.getBrandName() == null || brand.getBrandName().isEmpty()) {
            return RUtils.fail("品牌名称不能为空");
        }

        // 获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return RUtils.fail("用户未登录");
        }
        Long userId = Long.parseLong(authentication.getName());

        // 保存品牌信息
        boolean saved = save(brand);
        if (!saved) {
            return RUtils.fail("品牌创建失败");
        }

        // 获取STORE_OWNER角色ID
        Long roleId = roleMapper.selectOne(new QueryWrapper<Role>().eq("code", "STORE_OWNER")).getId();
        
        // 创建用户-角色关联
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(roleId);
        userRole.setBrandId(brand.getBrandId());
        userRoleMapper.insert(userRole);

        return RUtils.success("品牌创建成功", brand);
    }

    @Override
    public R updateBrand(Brand brand) {
        if (brand.getBrandId() == null || brand == null) {
            return RUtils.fail("参数错误");
        }
        Brand existingBrand = getById(brand.getBrandId());
        if (existingBrand == null) {
            return RUtils.fail("品牌不存在");
        }
        // 保留原有评分相关数据
        brand.setAverageRating(existingBrand.getAverageRating());
        brand.setPositiveReviewsCount(existingBrand.getPositiveReviewsCount());
        brand.setSalesVolume(existingBrand.getSalesVolume());
        boolean updated = updateById(brand);
        return updated ? RUtils.success("品牌更新成功", brand) : RUtils.fail("品牌更新失败");
    }

    @Override
    public Brand getBrandInfo(Long brandId) {

        Brand brand = getById(brandId);
        return brand;
    }

    @Override
    public R getBrandProducts(Long brandId) {
        if (brandId == null) {
            return RUtils.fail("品牌ID不能为空");
        }

        // 检查品牌是否存在
        Brand brand = getById(brandId);
        if (brand == null) {
            return RUtils.fail("品牌不存在");
        }

        // 查询该品牌下的所有商品
        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id", brandId);
        List<Product> products = productMapper.selectList(queryWrapper);

        return RUtils.success("获取品牌商品列表成功", products);
    }

    @Transactional(rollbackFor = Exception.class)
    public R handleSettleIn(Brand brand, Long userId) {
        // 保存品牌信息
        if (!save(brand)) {
            return RUtils.fail("品牌信息保存失败");
        }

        // 获取STORE_OWNER角色ID（根据数据库实际ID）
        Role storeOwnerRole = roleMapper.selectOne(
                new QueryWrapper<Role>().eq("code", "STORE_OWNER"));

        // 创建用户角色关联
        UserRole userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(storeOwnerRole.getId());
        userRole.setBrandId(brand.getBrandId());
        userRole.setCreateTime(LocalDateTime.now());

        if (userRoleMapper.insert(userRole) <= 0) {
            throw new RuntimeException("角色关联失败");
        }

        return RUtils.success("入驻成功", brand);
    }
}
